const mongoHelper = require('../../lib/MongoHelper.js');

module.exports = async function (router, settings) {
	const logger = settings.logger;
    let managercol = new mongoHelper.MongoCollection(settings['mongo_connect_url'], 'manager', 5);

	const renderErrorPage = function (res, err) {
        res.render('operation-result', {
            result: [false, err.toString()]
        });
    };

    const renderSuccessPage = function (res, information, jumpUrl) {
        res.render('operation-result', {
            result: [true, information, jumpUrl]
        })
    }

    const updatePassword = function(id, password, callback) {
        managercol.update(
        		id,
                {
                    'password': password,
                    'first_log_in': false
                },
                false,
                false
            ).then(ct=>{
                callback(ct);
            });
    }

	router.route('/profile/change-password').get((req, res) => {
        res.render('profile/change-password.html');
    }).post((req, res) => {
        let userid = res.locals.userid;
        let password = req.body.password;
        updatePassword(
        	userid,
        	password, 
	        (ct) => {
	            if (ct<1) {
	                logger.error('update password err =', err, 'username =', username);
	                renderErrorPage(res, 'modify error');
	            } else {
	                res.render('login', {
	                    'url': req.protocol + "://" + req.get('host') + req.originalUrl
	                });
	            }
	        }
        )
    });

    router.get('/profile/logout',(req,res)=>{
    	res.render('profile/log-out',{
    		'link' : req.protocol + '://u'+Math.ceil(Math.random()*1000)+'@' + req.get('host') + '/'
    	});
    });
}